$(function() {
	var cateWrap = $('#category .cateWrap');
	var showingCate, showingMenu;

	function hideCate() {
		if (showingCate != null) {
			showingCate.removeClass('hover');
			showingMenu.hide();
		};
	}

	function showCate(cate) {
		var currentCate = $(cate), subMenu = currentCate.children('.subMenu');
		return function() {
			hideCate();
			currentCate.addClass('hover');
			subMenu.show();
			var wrapTop = cateWrap.offset().top, scrollTop = $(window).scrollTop(),
				menuHeight = subMenu.height(), cateTop = currentCate.offset().top,
				cateBottom = cateTop + currentCate.height(),
				menuTop = wrapTop >= scrollTop ? wrapTop : scrollTop;
			var spare = 20;
			if (menuTop + menuHeight >= cateBottom + spare) {
				subMenu.css('top', menuTop - cateTop);
			} else {
				subMenu.css('top', cateBottom - cateTop + spare - menuHeight);
			};
			showingCate = currentCate;
			showingMenu = subMenu;
		};
	};
	
	var browser = $.browser, isIE9 = browser.msie === true && browser.version === '9.0';
	$('#category div.cate').each( function(n){
		if(!isIE9){
			var timer;
			$(this).hover(function(){
				// console.log($('.subMenu',this).size());
				$('.subMenu',this).show();
				timer = window.setTimeout(showCate(this), 25);
			}, function(){
				window.clearTimeout(timer);
				$('.subMenu',this).hide();
			});
		}else{//IE9特殊处理之
			$(this).hover(function(){
				$('.subMenu',this).show();
				showCate(this)();
			}, function(){
				hideCate();
				$('.subMenu',this).hide();
			});
		}
	});

			$('#category').mouseleave(function(){
			hideCate();
		});
});
